<?php
require_once 'application/libraries/AdMobApiClient.php';

class AdMobModel extends AdClientModel {

	private static $CLIENT_KEY = NULL;

	public function __construct() {
		$this->init();
	}

	private function init() {
		if ($this::$CLIENT_KEY == NULL) {
			$this::$CLIENT_KEY = $this->getClientKeyFromDB();
		}
		if ($this->api == NULL) {
			$this->api = new AdMobApiClient($this::$CLIENT_KEY);
		}
		$this->filter = new Admobfilter();
	}


	private function getSiteStatsData($site_id_array,$time_period,$time_dimension) {
		
		
		$start_date = DayHelper::getGmdate($time_period);
		$end_date = gmdate('Y-m-d'); // today

				
		$params = array(
				'site_id' => $site_id_array,
				'start_date' => $start_date,
				'end_date' => $end_date,
				'time_dimension' => $time_dimension,
				//'object_dimension' => AdMobApiClient::OBJECT_SITE,
				'order_by[date]' => 'desc'
		);
			
		$data = $this->api->getData('site', 'stats', $params, false);
		return $data;
	}

	private function getSiteSearchData($id) {
		$params = array() ;
		if ($id) {
			$params['site_id'] = $id;
		}
		$data = $this->api->getData('site', 'search', $params, false);
		return $data;
	}


	public function getData($operation,$email,$id,$time_period = "1",$time_dim = 'day',$data_needed) {
		$this->loginAndSetTtoken($email);
		$arr_response = array();
		try {
			$response = $this->execute($operation,$id, $time_period,$time_dim);
			MessagingHelper::AddToData($arr_response, $response);
		} catch (ApiException $ex) {
			$error_code = $ex->getCode();
			if ($error_code === 'token_invalid') {
				$this->login($email,$this->session->userdata('admobPassword'));
				try {
					$response = $this->execute($operation,$id, $time_period,$time_dim);
					MessagingHelper::AddToData($arr_response, $response);
				} catch (ApiException $ex1) {
					$response = $ex1->getApiResponse();
					MessagingHelper::AddToError($arr_response,ErrorMessgaes::$USER_ACOUNT_ADMOB_CODE ,$response);
				} catch (Exception $ex2) {
					MessagingHelper::AddToError($arr_response,ErrorMessgaes::$INERTNAL_CODE, ErrorMessgaes::$INERTNAL_MSG);
				}
			} else {
				$response = $ex->getApiResponse();
				MessagingHelper::AddToError($arr_response, ErrorMessgaes::$USER_ACOUNT_ADMOB_CODE,$response['errors']);
			}
		} catch (Exception $ex3) {
			MessagingHelper::AddToError($arr_response,ErrorMessgaes::$INERTNAL_CODE, ErrorMessgaes::$INERTNAL_MSG);
		}
		return $arr_response;
	}

	private function execute($operation,$id, $time_period,$time_dim) {
		if ($time_dim === 'day') {
			$time_dimension = AdMobApiClient::DIMENSION_DAY;
		} elseif ($time_dim === 'week') {
			$time_dimension = AdMobApiClient::DIMENSION_WEEK;
		} elseif ($time_dim === 'month') {
			$time_dimension = AdMobApiClient::DIMENSION_MONTH;
		}
		switch ($operation) {
			case 'statistics':
				$response = $this->getSiteStatsData($id, $time_period,$time_dim);
				return $this->filter->extract($response);
				
				break;
			case 'search':
				return $this->getSiteSearchData($id);
				break;

		}
	}

	private function loginAndSetTtoken($email) {
		$token = $this->session->userdata('admobToken');
		if (!$token || !isset($token)) {
			$this->getUserAccountData($email);
			$password = $this->session->userdata('admobPassword');
			if ($password) {
				$this->login($email,$password);
			}
		} else {
			$this->api->setToken($token);
		}
	}

	private function login($email,$password) {
		$this->api->login($email, $password);
		if (!$this->setToken($email,$this->api->getToken())) {
			throw new Exception("problem with saving token");
		} else {
			$this->session->set_userdata(array('admobToken' => $this->api->getToken()));
			$this->api->setToken($this->api->getToken());
		}
	}

	private function getClientKeyFromDB() {
		$sql = "SELECT client_keys.key FROM client_keys WHERE account_name = ?";
		$query = $this->db->query($sql, array('admob'));
		if ($query->num_rows() > 0) {
			$row = $query->row();
			return  $row->key;
		} else {
			throw new Exception('Problem fetching client key');
		}
	}

	protected function getUserAccountData($email) {
		$sql = "SELECT users_account_admob.account_token,users_account_admob.account_password FROM users_account_admob WHERE email = ?";
		$query = $this->db->query($sql, array($email));
		if ($query->num_rows() > 0) {
			$row = $query->row();
			$this->session->set_userdata(array('admobPassword' => ($row->account_password), 'admobToken' => ($row->account_token)));
		} else {
			throw new Exception('Problem fetching account data');
		}
	}

	private function getToken($email) {
		$sql = "SELECT users_account_admob.account_token FROM users_account_admob WHERE email = ?";
		$query = $this->db->query($sql, array($email));
		if ($query->num_rows() > 0) {
			$row = $query->row();
			return  $row->account_token;
		} else {
			throw new Exception('Problem fetching account token');
		}
	}

	private function setToken($email,$token) {
		$data = array(
				'account_token' => $token
		);

		$this->db->where('email', $email);
		return $this->db->update('users_account_admob', $data);

	}

	
	public function validateRequest($time_period,$time_dim) {
		$arr_resp = array();
	
		if (!($time_period)) {
			MessagingHelper::AddToError($arr_resp,ErrorMessgaes::$USER_ACOUNT_ADMOB_CODE, ErrorMessgaes::$USER_ADMOB_PARAMS_MISSING_MSG);
			$arr_resp =  $this->response($arr_resp);
		}
	
		if ($time_dim ==! 'day' || $time_dim ==! 'week' || $time_dim ==! 'month') {
			MessagingHelper::AddToError($arr_resp,ErrorMessgaes::$USER_ACOUNT_ADMOB_CODE, ErrorMessgaes::$USER_ADMOB_PARAMS_WRONG_DIM_MSG);
			$arr_resp =  $this->response($arr_resp);
		}
	
		return $arr_resp;
	}
	
	public function getSiteIdsArr($arr_resp) {
		$site_id_arr = array();
		if (!array_key_exists("error",$arr_resp) && array_key_exists("data",$arr_resp)) {
			foreach ($arr_resp['data'] as $entity) {
				array_push($site_id_arr,$entity['id']);
			}
		}
		return $site_id_arr;
	}
	
	

}
